<!--
 全部商品页面组件(包括全部商品,商品分类,商品搜索)
 -->
<template>
  <div class="goods" id="goods" name="goods">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item>全部商品</el-breadcrumb-item>
        <el-breadcrumb-item v-if="search">搜索</el-breadcrumb-item>
        <el-breadcrumb-item v-else>分类</el-breadcrumb-item>
        <el-breadcrumb-item v-if="search">{{search}}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 面包屑END -->

    <!-- 分类标签 -->
    <div class="nav">
      <div class="product-nav">
        <div class="title">分类</div>
        <el-tabs  type="card">
          <el-tab-pane
            v-for="item in categoryList"
            :key="item.catId"
            :label="item.catName"
            :name="''+item.catId"
          >
           <el-radio-group v-model="activeName" size="medium" >
            <el-radio-button v-for="item1 in item.children" :key="item1.catId"
             :label="item1.catId"  >{{item1.catName}}</el-radio-button>
          </el-radio-group>
          </el-tab-pane>
        </el-tabs>
        
      </div>
    </div>
    <!-- 分类标签END -->

    <!-- 主要内容区 -->
    <div class="main">
      <div class="list">
        <MyList :list="product" v-if="product.length>0"></MyList>
        <div v-else class="none-product">抱歉没有找到相关的商品，请看看其他的商品</div>
      </div>
    </div>
    <!-- 主要内容区END -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      categoryList: [], //分类列表
      categoryID: [], // 分类id
      product:  [], // 商品列表
      productList: "",
      activeName: "-1", // 分类列表当前选中的id
      search: "" // 搜索条件
    };
  },
  activated() {
     // 获取分类列表
    this.getCategory();
    this.activeName = "-1"; // 初始化分类列表当前选中的id为-1
    this.total = 0; // 初始化商品总量为0
    this.currentPage = 1; //初始化当前页码为1
    // 如果路由没有传递参数，默认为显示全部商品
    if (Object.keys(this.$route.query).length == 0) {
      this.categoryID = [];
      // console.log("qubu")
      this.activeName = "0";
      return;
    }
    // 如果路由传递了categoryID，则显示对应的分类商品
    if (this.$route.query.categoryID != undefined) {
      this.categoryID = this.$route.query.categoryID;
      if (this.categoryID.length === 1) {
        this.activeName = "" + this.categoryID[0];
      }
      return;
    }
    // 如果路由传递了search，则为搜索，显示对应的分类商品
    if (this.$route.query.search != undefined) {
      this.search = this.$route.query.search;
    }
  },
  watch: {
    // 监听点击了哪个分类标签，通过修改分类id，响应相应的商品
    activeName: function(val) {
      if (val == 0) {
        this.categoryID = [];
      }
      if (val > 0) {
        this.categoryID = [Number(val)];
      }
      // 初始化商品总量和当前页码
      this.total = 0;
      this.currentPage = 1;
      // 更新地址栏链接，方便刷新页面可以回到原来的页面
      this.$router.push({
        path: "/goods",
        query: { categoryID: this.categoryID }
      });
    },
    // 监听搜索条件，响应相应的商品
    search: function(val) {
      if (val != "") {
        this.getProductBySearch(val);
      }
    },
    // 监听分类id，响应相应的商品
    categoryID: function() {
      this.getData();
      this.search = "";
    },
    // 监听路由变化，更新路由传递了搜索条件
    $route: function(val) {
      if (val.path == "/goods") {
        if (val.query.search != undefined) {
          this.activeName = "-1";
          this.currentPage = 1;
          this.total = 0;
          this.search = val.query.search;
        }
      }
    }
  },
  methods: {
    // 返回顶部
    backtop() {
      const timer = setInterval(function() {
        const top = document.documentElement.scrollTop || document.body.scrollTop;
        const speed = Math.floor(-top / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          top + speed;
        if (top === 0) {
          clearInterval(timer);
        }
      }, 20);
    },
    // 向后端请求分类列表数据
    //   获取所有的商品分类列表
    async getCategory () {
      const {data:res} = await this.$http.get("/xuanmall/category/list/tree")
        if(res.code === 0){
         this.categoryList = this.formatData(res.data)
        //  console.log(this.categoryList)
        }
    },
    // 格式化数据，递归将空的children置为undefined
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatData(data[i].children)
        }
      }
      return data
      },
     
    // 向后端请求全部商品或分类商品数据
    async  getData() {
      // 如果分类列表为空则请求全部商品数据，否则请求分类商品数据
      // const {data:res} = await this.$http(`/xuanmall/spumessage/getAllShopByCatalogId?catalogId=${this.categoryID}&page=${this.pageIndex}&limit=${this.pageSize}`)
     const {data:res} = await this.$http(`/xuanmall/spumessage/getAllShopByCatalogId?catalogId=${this.categoryID}&page=1&limit=200`)
      console.log("所有商品",res)
      this.product = []
      res.page.list.forEach(value =>{
        if(value.publishStatus){
        var data = {};
         data.product_id = value.id
         data.product_name = value.spuName
         data.product_picture = value.images[0]
         data.product_selling_price = value.price
         data.product_num = 0
         value.skus.forEach(item =>{
           data.product_num += item.saleCount
         })
         this.product.push(data)}
      })
      // console.log("this.product",this.product)
    },
    // 通过搜索条件向后端请求商品数据
    getProductBySearch() {
      this.$http
        .post(`/xuanmall/spumessage/getAllShopByCatalogId?key=${this.search}`)
        .then(res => {
          // console.log("res",res)
          this.product =[]
          res.data.page.list.forEach(value =>{
            var data = {};
            data.product_id = value.id
            data.product_name = value.spuName
            data.product_picture = value.images[0]
            data.product_selling_price = value.price
            data.product_num = 0
            value.skus.forEach(item =>{
              data.product_num += item.saleCount
            })
            this.product.push(data)
          })
        })
        .catch(err => {
          return Promise.reject(err);
        });
    }
  }
};
</script>

<style scoped>
.goods {
  background-color: #f5f5f5;
}
/* 面包屑CSS */
.el-tabs--card .el-tabs__header {
  border-bottom: none;
}
.goods .breadcrumb {
  height: 50px;
  background-color: white;
}
.goods .breadcrumb .el-breadcrumb {
  width: 1225px;
  line-height: 30px;
  font-size: 16px;
  margin: 0 auto;
}
/* 面包屑CSS END */

/* 分类标签CSS */
.goods .nav {
  background-color: white;
}
.goods .nav .product-nav {
  width: 1225px;
  height: 40px;
  line-height: 40px;
  margin: 0 auto;
}
.nav .product-nav .title {
  width: 50px;
  font-size: 16px;
  font-weight: 700;
  float: left;
}
/* 分类标签CSS END */

/* 主要内容区CSS */
.goods .main {
  margin: 0 auto;
  max-width: 1225px;
}
.goods .main .list {
  min-height: 650px;
  margin-top: 50px;
  padding-top: 14.5px;
  margin-left: -13.7px;
  overflow: auto;
}
.goods .main .pagination {
  height: 50px;
  text-align: center;
}
.goods .main .none-product {
  color: #333;
  margin-left: 13.7px;
}
/* 主要内容区CSS END */
</style>